import Vue 			from 'vue'
import util 		from '../../util'
import { Toast,Dialog,List } 	from 'vant';
Vue.use(Toast,Dialog,List);

export default {
	name: 'redhome',
	data(){
		return {
			uid:'',				//当前用户UID
			token:'',
			totalBtc:0,			//持有的BTC数量
			redList:[],			//红包列表
			socket:'',			//socket连接
			taskListObj:'',		//任务列表信息
			markBox:false,		//是否显示领红包弹窗
			redItem: {
				nickname:'',
				url:'',
				btc:'',
				coinType:'BTC',
				bsflag:'',
				redid:''
    		},
    		clickBtn:false,		//防止重复点击
    		waitRedResult:false,//是否等待领取结果中
    		getResult:[],		//已领取
    		random:0,			//随机数(动态排列红包)
    		topDistance:0,		//滚动距离顶部距离
		}
	},
	computed:{
		scrollList(){
			//滚动任务列表
			return this.redList.concat(this.redList).concat(this.redList)
		},
		taskList(){
			//任务列表
			if(!this.taskListObj) return [];
			let dataitem = this.taskListObj;
			let arr = [];
			if(this.taskListObj && this.taskListObj.list && this.taskListObj.list.length){
				this.taskListObj.list.forEach(item => {
					arr.push({
						title: item.title,
						logo:item.logo,
				        des: item.nums,
				        tasskType:item.tasskType,
				        actionName:item.actionName,
				        // type: 3,
				        perCount: item.times,
				        num: item.wait * item.times,
				        enabled: item.wait > 0 || Number(item.nums) < 1,
				        wait:item.wait
					})
				})
			}
			return arr;
			// return [
			// 	{
			//         title: '完成一次快捷买币或充币',
			//         des: dataitem.inmoney_nums+'/1',
			//         type: 3,
			//         perCount: 5,
			//         num: dataitem.inmoney_wait * 5,
			//         enabled: dataitem && (dataitem.inmoney_wait > 0 || Number(dataitem.inmoney_nums) < 1),
			//         wait:dataitem && dataitem.inmoney_wait
			//     },
			//     {
			//         title: '使用USDT完成一次闪电合约交易',
			//         des: dataitem.order_nums+'/1',
			//         type: 7,
			//         perCount: 10,
			//         num:dataitem && dataitem.order_wait * 10,
			//         enabled:dataitem && (dataitem.order_wait > 0 || Number(dataitem.order_nums) < 1),
			//         wait:dataitem && dataitem.order_wait
			//     },
			//     {
			//         title: '使用USDT完成一次永续合约交易',
			//         des: dataitem.swap_nums+'/1',
			//         type: 9,
			//         perCount: 10,
			//         num: dataitem && dataitem.swap_wait * 10,
   //        			enabled:dataitem && (dataitem.swap_wait > 0 || Number(dataitem.swap_nums) < 1),
   //        			wait: dataitem && dataitem.swap_wait,
			//     },
			// 	{
			//         title: '邀请好友完成注册',
			//         des: dataitem.invite_nums+'/1',
			//         type: 2,
			//         perCount: 10,
			//         num: dataitem && dataitem.invite_wait * 10,
   //        			enabled:dataitem && (dataitem.invite_wait > 0 || Number(dataitem.invite_nums) < 1),
   //        			wait: dataitem && dataitem.invite_wait,
			//     }
			// ]
		}
	},
	methods:{
		/*  gotoTradeView    完成交易、止盈、爆仓
  			gotoDeposit   充值
  			gotoShareTimeNews 分享新闻或者快讯
  			gotoInviteFriend 邀请好友
  			gotoRealName  实名认证
  		 */
		openTaskAction(tasskType,actionName,num){
			// let actionName = '';
		 //    let taskType = '';
		 //    let guessNum = 0;
		 //    switch (type) {
		 //    	case 3:
		 //        	taskType = 'inmoney';
		 //        	actionName = 'gotoDeposit';
		 //        	break;
		 //    	case 7:
		 //        	taskType = 'order';
		 //        	actionName = 'gotoTradeView';
		 //        	break;
		 //        case 9:
		 //        	taskType = 'swap';
		 //        	actionName = 'tradeHome';
		 //        	break;
		 //      	case 2:
		 //        	taskType = 'invite';
		 //        	actionName = 'gotoInviteFriend';
		 //        	break;
		 //    }

		    if (num > 0) {
		    	Toast(this.$t('redHome-key19'));
		      	this.getRedpackageCountAction(tasskType);
		      	return;
		    }
		    if(this.version >= 412){
		    	// console.log(actionName)
		    	util.callHandler('openUrl',{
					url:util.trim(actionName),
					title:'',
					needLogin:true,
					popVC:true,		//跳转的时候是否干掉当前页面
					hiddenNav:true,	//是否全屏
				},res => {
					console.log(res)
				})
		    }else{
		    	if (tasskType === 'inmoney') {
			    	//充值成功1次
			    	util.callHandler('openUrl',{
						url:window.location.origin+'/otc/index.html#/?uiEdit=1',
						title:'',
						needLogin:true,
						popVC:true,		//跳转的时候是否干掉当前页面
						hiddenNav:true,	//是否全屏
					},res => {
						console.log(res)
					})
			    }else if(tasskType === 'order'){
			    	//使用USDT交易1次
			    	util.callHandler('openUrl',{
						url: 'bbjApp://tradeHome',
						title:'',
						needLogin:false,
						popVC:false,		//跳转的时候是否干掉当前页面
		                hiddenNav:false,	//是否全屏
		                type: 'CFD'
					},res => {
						console.log(res)
					})
			    }else if (tasskType === 'swap') {
			    	//完成一次永续合约交易
			      	util.callHandler('openUrl',{
						url: 'bbjApp://tradeHome',
						title:'',
						needLogin:false,
						popVC:false,		//跳转的时候是否干掉当前页面
		                hiddenNav:false,	//是否全屏
		                type: 'inverse'
					},res => {
						console.log(res)
					})
			    }else if(tasskType === 'invite'){
			    	//邀请好友完成注册
			    	util.callHandler('openUrl',{
						url:window.location.origin+'/otc/index.html#/invite',
						title:'',
						needLogin:true,
						popVC:true,		//跳转的时候是否干掉当前页面
						hiddenNav:true,	//是否全屏
					},res => {
						console.log(res)
					})
			    }else{
			    	Toast(this.$t('goUpdate'))
			    }
		    }
		},
		getRedpacket(){
			if(this.clickBtn) return
			this.clickBtn = true;
			if(Number(this.taskListObj.total) == 0) return;
			//领取红包动作
			if(this.socket && this.socket.readyState === 1){
				this.waitRedResult = true;
				const data = {
			    	mtype: 1011,
			      	data: {
			        	redid: this.redItem.redid,
			        	token: this.token,
			      	}
			    };
			    //判断缓存中是否已领过当前红包
			    let redListStorage = window.localStorage.getItem('redListStorage');
			    if(redListStorage) redListStorage = JSON.parse(redListStorage);
			    if(redListStorage && redListStorage.find(item => item.redid === this.redItem.redid && item.uid === this.uid)){
			    	Toast(this.$t('redHome-key20'));
			    	this.waitRedResult = false;
			    	this.clickBtn = false;
			    	return
			    }
            	this.socket.send(JSON.stringify(data))
			}else{
				Toast(this.$t('redHome-key21'))
			}
			
		},
		showMark(item){
			if(item && item.hasGot){
				//已领过
				this.$router.push({
					path:'/redetails',
					query:{
						rid:item.redid,
						type:1,
						// info:encodeURIComponent(JSON.stringify(getParams)),
						title:'',
					}
				})
				return
			}
			if(Number(this.taskListObj.total) == 0) {
				Toast(this.$t('redHome-key22'));
				return
			}
			if(item.out || item.hasgot) return
			//显示红包弹窗
			this.redItem = {
             	nickname : item.nickname,
                url : item.url,
              	btc : item.amount,
                coinType : 'BTC',
                bsflag : item.bsflag,
                redid:item.redid
            };
            this.markBox = true;
		},
		binaryData(ev) {
    		try {
      			return JSON.parse(
        			new TextDecoder('utf-8').decode(new Uint8Array(ev.data))
      			);
    		} catch (e) {
      			return '';
    		}
  		},
		getRedpackageCountAction(s) {
    		util.fetch2(`${util.ajaxUrl}/red-packet/add-times?type=`+s,{}).then(res => {
    			if(res && res.retCode === 0){
    				Toast(this.$t('redHome-key23'));
    				this.getTaskList();
    			}else{
    				Toast(res.retMsg)
    			}
    		})
  		},
		// showOutMoney(){
		// 	//点击提现按钮
		// 	util.callHandler('openUrl', {
		// 		url: 'bbjApp://inOutCoin?type=out&coin=BTC',
		// 		title : '提币',
		// 		needLogin : true
  // 			})
		// },
		getTotalBTC(){
			//获取持有的BTC数量
			util.fetch2(`${util.ajaxUrl}/red-packet/total`,{}).then(res => {
				if(res.retCode === 0){
					this.totalBtc = util.formatBTC(res.retData.total);
				}else{
					Toast(res.retMsg || res.retHtml || this.$t('noError'))
				}
			})
		},
		setRedListStorage(item){
			//缓存已领取的红包列表
			let redListStorage = window.localStorage.getItem('redListStorage');
			let newArr = [];
			if(!redListStorage){
				newArr.push(item);
			}else{
				redListStorage = JSON.parse(redListStorage);
				let _find = redListStorage.find(ele => ele.redid === item.redid && item.uid === ele.uid);
				if(!_find) redListStorage.push(item);
			}
			window.localStorage.setItem('redListStorage',redListStorage?JSON.stringify(redListStorage):JSON.stringify(newArr))
		},
		transferType(bsflag,is_sp){
			let trarget = '';
			// console.log(bsflag)
			switch (bsflag) {
           		case 2:trarget = this.$t('redHome-key26');break;
           		case 3:trarget = this.$t('redHome-key27');break;
              	case 4:if(is_sp == 1){trarget = this.$t('redHome-key28')}else{trarget = this.$t('redHome-key29')};break;
            	// case 5: trarget = '止盈平仓';break;
            	case 5: trarget = this.$t('redHome-key30');break;
              	// case 6: trarget = '止损平仓';break;
              	case 6: trarget = this.$t('redHome-key30');break;
				case 7: trarget = this.$t('redHome-key31');break;
            	case 8: trarget = this.$t('redHome-key32');break;
            	case 9: trarget = this.$t('redHome-key33');break;
            	case 10: trarget = this.$t('redHome-key30');break;
				default: trarget = '';
            }
            return trarget
		},
		calcDistance(){
			//计算滚动距离
			let max = this.scrollList.length;
			let _topDistance = this.topDistance+1;
			_topDistance > max-1?_topDistance=0:null;
			// console.log(max)
			this.topDistance = _topDistance;
			setTimeout(()=>{
				this.calcDistance();
			},3000)
		},
		initSocket(){
			//初始化websocket
			if(this.socket) return
			this.socket = new WebSocket(util.wssUrl);
	        this.socket.onopen = () => {
	            if (!this.socket || (this.socket && this.socket.readyState != 1)) return
	        }
	        this.socket.binaryType = 'arraybuffer';
	        this.socket.onmessage = evt => {
	        	if (evt.data) {
		        	const res = this.binaryData(evt);
		        	if(!res) return
		        	if(res.mtype === 1010){
		        		//红包列表
		        		let redListStorage = window.localStorage.getItem('redListStorage');
			    		if(redListStorage) redListStorage = JSON.parse(redListStorage);
			    		res.data.map(item => {
		    				item.hasGot = (redListStorage && redListStorage.find(ele => ele.uid === this.uid && ele.redid == item.redid))?true:false,
		    				item.out = false;
		    				item.typeName = this.transferType(item.bsflag,item.is_sp)
		    			})
		        		this.redList = res.data;
		        		// console.log(res.data)
		        	}else if(res.mtype === 1011){
		        		this.clickBtn = false;
		        		this.markBox = false;
		        		this.waitRedResult = false;
		        		// console.log(res)
		        		if(res.code === 0 && res.hasgot){
		        			//已领过
		        			Toast(this.$t('redHome-key24'));
		        			this.setRedListStorage({
								redid:this.redItem.redid,
								bsflag:this.redItem.bsflag,
								hasGot:true,
								uid:this.uid
							})
		        		}else if(res.code === 0 && !res.hasgot){
		        			this.getTotalBTC();
		        			//领取成功
		        			this.getResult = res.data;
		        			this.taskListObj.total = this.taskListObj.total - 1;
		        			this.setRedListStorage({
								redid:this.redItem.redid,
								bsflag:this.redItem.bsflag,
								hasGot:true,
								uid:this.uid
							})
							const getParams = {
				            	nickname: this.redItem.nickname,
				            	url: this.redItem.url,
				            	btc: res.amount,
				            	coinType: '',
				            	bsflag : this.redItem.bsflag
				            };
				            setTimeout(()=>{
				            	this.$router.push({
									path:'/redetails',
									query:{
										rid:this.redItem.redid,
										type:1,
										info:encodeURIComponent(JSON.stringify(getParams)),
										title:'',
									}
								})
				            },300)
		        		}
		        		this.redList.map(item => {
	        				if(item.redid === this.redItem.redid){
	        					item.hasGot = true;
	        				}
	        			})
		        	}
		      	}
	        }
	        
	        this.socket.onerror = err => {
	        	Toast(this.$t('redHome-key21'));
	            console.log(err)
	        }
		},
		getTaskList(){
			//任务列表
			if(window.localStorage.getItem('taskListObj')){
				this.taskListObj = JSON.parse(window.localStorage.getItem('taskListObj'))
			}
			util.fetch2(`${util.ajaxUrl}/red-packet/task-list-new`,{}).then(res => {
				Toast.clear();
				if(res.retCode === 0){
					this.taskListObj = res.retData;
					window.localStorage.setItem('taskListObj',JSON.stringify(this.taskListObj));
				}else{
					Toast(res.retMsg || res.retHtml || this.$t('noError'))
				}
			})
		},
		getUid(){
			//拉取用户UID
			util.fetch(`${util.ajaxUrl}/otc/otc-config`,{}).then(res => {
				if(res.retCode === 0){
					this.uid = res.retData.uid;
					this.initSocket();
				}
			})
		},
		init(){
			// setInterval(()=>{
			// 	console.log(this.taskList)
			// },2000)
			let _random = window.localStorage.getItem('redSortNum');
			this.random = Number(_random?_random:0)+1;
			window.localStorage.setItem('redSortNum',this.random >= 5?0:this.random);
			this.getTotalBTC();
			this.getUid();
			this.getTaskList();
			this.calcDistance();
		},
		goBack(){
			util.navigateBack(-1,this)
		}
	},
	created() {
		document.querySelector('body').setAttribute('style', 'background:#3a9f81');
		util.waitSDKReady().then(token => {
			this.token = token;
			this.init();
		}).catch((e) => {
			Toast(this.$t('getTokenFail'))
		})
		setTimeout(() => {
			util.registerHandler('refreshCommonRequestWhenGoBackView',res => {
				if(this.token) this.getTotalBTC();
				if(this.token) this.initSocket();
				if(this.token) this.getTaskList();
				util.callHandler('setStatusBarStyle',{
					style:'dark'
				})
			})
		},500)
    },
    beforeDestroy(){
    	document.querySelector('body').setAttribute('style', '');
    }
}